const multer = require("multer");
const { resolve, extname, join } = require("path");
const fs = require("fs");
const { UPLOAD_URL } = require("../config");
const { Send } = require("../utils/response");

class CommonController {
    static async upload(req, res, next) {
        try {
            // 创建上传目录
            const storage = multer.diskStorage({
                destination: function (req, file, cb) {
                    if (!fs.existsSync(resolve(__dirname, "../uploads"))) {
                        fs.mkdirSync(resolve(__dirname, "../uploads"));
                    }
                    cb(null, resolve(__dirname, "../uploads"));
                },
                filename: function (req, file, cb) {
                    const uniqueSuffix =
                        Date.now() + "-" + Math.round(Math.random() * 1e9);
                    const ext = extname(file.originalname);
                    cb(null, uniqueSuffix + ext);
                },
            });
            // 创建上传过滤器
            const filter = function (req, file, cb) {
                const ext = extname(file.originalname).toLowerCase(),
                    allows = [".png", ".jpg", ".jpeg", ".gif"];
                if (allows.includes(ext)) {
                    cb(null, true);
                } else {
                    cb(new Error("上传格式不支持"));
                }
            };
            // 创建上传
            const uploader = multer({
                storage,
                fileFilter: filter,
                limits: { fileSize: 1024 * 1024 * 5, files: 1 },
            }).single("file");
            uploader(req, res, function (err) {
                if (err) {
                    return Send(res, {
                        code: -1,
                        message: err.message || "上传失败",
                    });
                }
                if (!req.file) {
                    return Send(res, {
                        code: -1,
                        message: "上传文件不存在",
                    });
                }
                Send(res, {
                    message: "上传成功",
                    data: {
                        url: `${UPLOAD_URL}/${req.file.filename}`,
                    },
                });
            });
        } catch (error) {
            next(error);
        }
    }
    static async minupload(req, res, next) {
        try {
            Send(res, {
                message: "压缩上传webp成功",
            });
        } catch (error) {
            next(error);
        }
    }
}

module.exports = CommonController;
